LScript User Guide
Next Section Previous Section Table of Contents Index Errata

Built-In Features

Each LScript, regardless of architecture, can access attributes that are built into the LScript engine. These "built-ins" consist of pre-defined values, commands and functions. Each of these constants can be used anyplace you would employ a user-defined variable, with the exception that their values cannot be modified (i.e., they cannot be used on the left side of an assignment statement).

Pre-defined Values

A number of constant (read-only) variables are available to each LScript. Most have some direct relation to a Modeler command. They are:

     PI             E              GAMMA
     DEG            PHI            READ
     WRITE          APPEND         VERTICAL
     HORIZONTAL     FROMSTART      FROMEND
     FROMHERE       INTEL          ALPHA
     SGI            MIPS           MACINTOSH
     AMIGA          CREATE         ATTACH
     AUTOCLEAR      LAYOUT         MODELER
     SCREAMERNET    nil            true/TRUE
     false/FALSE    X              Y
     Z
Scripts destined for use under LightWave Modeler have these additional values pre-defined for their use:
     GAUSSIAN       UNIFORM        NORMAL
     SHARP          BUFFERED       KNOTS
     SUBTRACT       INTERSECT      ADD
     LENGTHS        CORE           TUNNEL
     STENCIL        SLICE          FLAT
     SMOOTH         METAFORM       SET
     CLEAR          VOLUME         CONNECT
     NPEQ           NPLT           NPGT
     VOLEXCL        VOLINCL        SURFACE
     NVEQ           NVLT           NVGT
     CURVE          NONPLANAR      SELECTED
     FACE           UNSELECTED     ABORT
     START          END            DETAIL
     GLOBAL         USER           RADIAL
     UNION          POLYNDX        POLYID
     POINTNDX       POINTID
LightWave 3D Layout scripts have access to their own set of global constant values:
     SCENEMODE      OBJECTMODE     MESH
     LIGHT          CAMERA         BONE
     SCENE          POSITION       RIGHT
     UP             FORWARD        ROTATION
     SCALING        PIVOT          WPOSITION
And, specific architectures under LightWave 3D Layout also their own specialized values:

Image Filter

     SPECIAL        LUMINOUS       DIFFUSE
     SPECULAR       MIRROR         TRANS
     RAWRED         RAWGREEN       RAWBLUE
     SHADING        SHADOW         GEOMETRY
     DEPTH          RED            GREEN
     BLUE           ALPHA

Procedural Texture

     NORMAL         COLOR          LUMINOUS
     DIFFUSE        SPECULAR       MIRROR
     TRANSPARENT    ETA            ROUGHNESS
     RAYTRACE

Displacement Map

     WORLD          LOCAL

Object Replacement

     NONE           PREVIEW        RENDER
For more information on the uses of the Modeler-specific constants, please refer to the later sections of this User's Guide that document
LScript's Modeler-specific commands.

For information on the uses of the Layout-specific constants, please refer to the sections of this User's Guide that document LScript's Layout-specific commands.

Internal Commands

LScript makes available to the script programmer a number of generic, built-in commands. These functions are not directly related to either LightWave 3D Modeler or Layout, and both their calling syntax and usage are documented in the following sections.

angle

This function will return the angle, in degrees, between two points on a specified plane (XZ, YZ, or XY). It accepts two vectors representing the two points, and a third parameter that specifies the axis perpendicular to the plane in which the angle should be calculated.

You might invoke this function in the following manner:

     ...
     editbegin();
       pnt1 = pointinfo(points[1]);
       pnt2 = pointinfo(points[2]);
     editend();

     info(angle(pnt1,pnt2,X),    // return angle in the YZ plane
          " degrees");
     ...

sqrt

This function calculates the square root of a number. It accepts a numeric value, and returns the square root of that value.

You might invoke this function in the following manner:

     ...
     angle = 180;    // 180 degrees
     varSquare = sqrt(angle);  // calc square root of angle
     ...

exp

This function calculates the exponent of a value. It accepts a numeric value, and returns the exponent of that value.

An example of its usage might be:

     ...
     v1 = exp(27.5);
     ...

log

This function calculates the logarithmic value of a number. It accepts a number, and returns the logarithmic value of that number.

An example of its usage might be:

     ...
     v1 = log(347.495);
     ...

sin asin cos acos tan atan cosh sinh tanh sec cot csc

These functions calculate the trigonometric value of an angle, specified in radians. They accept a numeric radian angle, and return the operation result of that value.

The functions sinh(), tanh(), and cosh() calculate the hyperbolic values of their respective functions.

An example of their usage might be:

     ...
     sin1 = sin(45);
     ...
     asin1 = asin(276);
     ...

abs

This function returns the absolute value of a number. Regardless of the sign of the number, the return value from this function is always positive.

     ...
     if(abs(decline) > 30)
     ...

ceil floor

The ceil() function returns the smallest integer value that is greater than or equal to the numeric value passed as an argument. The floor() function returns the largest integer value that is less than or equal to its numeric parameter.

     ...
     c = ceil(45.6);
     f = floor(13.3);
     ...

random

This function offers an LScript the ability to generate pseudo-random integer numbers. It accepts two numeric integer values, and returns a random integer number that lies between those two numbers (inclusive). Numbers can be negative or positive.

An example of its usage might be:

     ...
     triggerFrame = random(20,50);
     ...

randu

This function returns a random number that lies between 0 and 1.

     ...
     rad = 0.05 * maxlen * (1 + randu())
     ...

min max

The min() function returns the smaller of its two numeric arguments, while max(), the inverse, returns the larger.

     ...
     t = min(top,7);
     ...

mod

The mod() function returns the modulo--or remainder--of the division when its first numeric argument is divided by its second. The LScript operator % can also be used as a substitute for this functionality.

     ...
     t = mod(34.5,6);  // returns 4.5
     ...
or, alternately,

     ...
     t = 34.5 % 6;
     ...

pow

The pow() function raises its first numeric argument to the power specified by its second.

     ...
     t = pow(5,3);  // returns 125
     ...

hypot

The hypot() function calculates the hypotenuse of the right triangle whose sides correspond to the functions first and second numeric arguments.

     ...
     t = hypot(3,5);
     ...

rad deg

These two functions, rad() and deg(), are conversion utilities. The rad() function will accept a single numeric angle parameter, specified in degrees, and convert it to radians. The deg() function will accept a single numeric angle parameter, specified in radians, and convert it to degrees.

     ...
     t = rad(degrees); // equivalent to: degrees * (PI / 180)
     ...

range

The range() function determines if its first numeric parameter falls within the range of numeric values specified by its second and third, inclusively. It returns a Boolean value (true or false).

     ...
     if(range(top,3,8))
     ...

selector

The selector() function compares its first two numeric parameters, and returns its third parameter if the first comparitor is less than the second, or returns its fourth parameter if the first comparitor is greater than or equal to the second.

     ...
     t = selector(4,7,15,3); // returns 15
     ...
     t = selector(15,7,7,10); // returns 10
     ...

step

The step() function evaluates its two numeric arguments, and returns 0 if the second value is less than the first, or returns its third numeric parameter if the second value is greater than or equal to the first.

     ...
     t += step(y,10,.25); // step by .25
     ...

round

The round() function will round a numeric value to decimal place specified in the second integer parameter. If this second value is zero (0), then the numeric value will be rounded to the nearest whole integer.

     ...
     t = round(37.7,0);  // returns 38
     t = round(4.4394,2);  // returns 4.44
     ...

frac

The frac() function returns the fraction portion of a numeric value.

     ...
     t = frac(46.75);  // returns 0.75
     ...

fac

The fac() command will calculate the factorial value of the provided numeric parameter.

     ...
     t = fac(5);  // returns 120
     ...

vmag

The vmag() function calculates the magnitude of a three-dimensional vector.

     ...
     t = vmag(x,y,z); // calculate magnitude of my location
     ...

info, warn, error

Each of these commands take a variable number of parameters, each of which can be of any of the supported data types (except array), and issues the appropriate message type to the user.

     ...
     error("Value ",val," exceeds max limit of ",
               10 * items," items");
     ...

File

This command accepts a string indicating the location of a disk file, and an optional mode string to indicate how the file should be opened, and returns a File Object. Please refer to the section earlier in this document that discussed
LScript Objects for an explanation of this particular object and its methods.

     ...
     sceneFile = File("/temp.lws","w");
     ...
File open modes are identical to those provided by C. They are:

     r    read (ascii)
     w    write (ascii)
     a    append (ascii)
     b    binary (i.e., "rb" would be read-binary)
     +    with update (i.e., the file pointer can be moved arbitrarily)
For instance, to open a file for random binary read access, you would specify "rb+" as the open mode for your file.

If the optional open mode value is not specified, then the file will be opened in read-ascii ("r") mode by default.

fileexists

This command returns a boolean value (true/false) indicating the existence of the specified file. Like the info()/warn()/error() commands discussed earlier, this command takes a variable number of arguments that it will use to construct a string that should evaluate to the filename.

In this example, we employ LScript's string math feature to build the final filename.

     index = 9;
     ...
     if(fileexist("/temp" + index + ".lwo"))   // filename becomes "/temp9.lwo"
     ...

filedelete

This command will attempt to remove the disk file specified. As with fileexists(), this command also accepts a variable number of arguments that it will use to construct a string that should evaluate to the filename. This command returns the status of its success, where 0 indicates no error occurred.

     index = 1;
     ...
     if(filedelete("\\temp",index,".lwo"))
         error("Cannot remove file \\temp",index,".lwo!);
     ...

center

Given two points in three-dimensional space, this command will return the center point that lies between them. This command accepts a number of different parameter counts and types: an array whose first two elements are vectors, two vectors (either as a constant or as variables), or six numeric values where the first three represent the first vector, and the next three represent the second vector.

center() returns a vector data type.

     // since boundingbox() returns two vectors, we
     // can just feed its output to center()

     objectCntr = center(boundingbox());

extent

This command accepts the same number/types of arguments as center(), but instead of calculating the center of a pair of vectors, it will return the extents (distances) between the two points.

extent() returns a vector data type, whose elements (x,y,z) represent the extents along each of those axes.

     objectSize = extent(boundingbox());

parse

parse() will accept two parameters, the first being a string of potential token separators and the second the character string to process. This function returns an array of tokens of which the string (second parameter) is comprised.

     str = "23,45,69.6,100";

     tokens = parse(",",str);  // returns "23", "45", "69.9"
                                   // and "100"
     ...

size

This command is used to determine the size of a particular variable of a particular data type. For numeric values, it returns 1. For vectors types, it returns 3. Character string arguments return the number of characters in the string, while array arguments return the number of actual elements in the array (not the total size of the array).

     str = "23,45,69.6,100";

     tokens[10] = nil;

     t = size(tokens);  // returns 0

     tokens = parse(",",str);  // returns four elements

     t = size(tokens);  // returns 4

     tokens[8] = 1.0;

     t = size(tokens);  // returns 5
     ...

number, integer

number() takes a string argument and attempts to convert it into a numeric (floating point) value. integer() takes the same argument type, but returns an integer value. For integer(), if the character string includes a decimal point, it will be stripped. To round a floating point value up or down, use the round() function.

These functions will extract values from a character string, even if the numeric values do not appear that the beginning of the string.

     str = "69.6";

     t = number(str);                        // returns 69.9
     t = integer(str);                       // returns 69
     t = integer(round(number("69.9")));     // returns 70
     t = number("The answer is: .1593");     // returns .1593
     ...

vector

This command takes a string argument and attempts to convert it into a vector.

     str = "4 6.5 8";
     t = vector(str);  // returns <4,6.5,8>
     ...

string

This command takes a variable number of arguments, each of which can be any of the supported LScript data types (except array), and constructs a character string.

     t = string("Value ",val," exceeds max limit of ",
                    10 * items," items");

split

split() is designed to work specifically with file path/name character strings. It will accept a character string, and return an array of four (4) elements representing the drive, path, filename, and filename extension that could be derived from the string argument.

     file = getfile("Select A Scene...","*.lws");
     if(file == nil)
          return;

     if(fileexists(file))
     {
         base = split(file);  // get the components (base becomes an array)
         ...
Components of the string that do not exist (i.e., no drive designation) will be returned as nil.

append

This command provides services for both character strings and arrays. It will append a value of any supported LScript integral data type to the end of a string as a sequences of characters, or to an LScript array as a new element.

Arrays can also be appended to other arrays using this function.

spawn

This command will begin the execution of an external process under Microsoft Windows NT or Windows 95. Normally, the entire execution of the external process will take place within this command. In this case, the spawn() command will return the execution result code for the specified process.

However, if the asyncspawn pragma directive has been declared in the script, then the spawn() command will, upon success, return the process id of the external process it launched. This process id is required as an argument to the other process control functions wait() and terminate().

     // launch ScreamerNet II in parallel

     snID = spawn("lwsn -2 ",
               getenv("TMP"),"\\snii.job ",
               getenv("TMP"),"\\snii.rpl");

     if(snID == nil)
     {
         error("Cannot create ScreamerNet process");
         ...

wait

This command is provided as a synchronization function for spawn(). Passed a process id (which is returned by spawn()), this command will halt script execution until the specified external process terminates, and will then return the exit status of that process.

terminate

Another function in the process control suite of commands, terminate() will cause the specified process id to be terminated by Windows.

     terminate(snID);    // shut down ScreamerNet

getenv

Just like its C counterpart, this function will accept a string argument--which is presumed to be an environment variable--and will return the current value of the variable. If no variable exists in the environment with the provided name, getenv() will return nil.

     tempfile = getenv("TMP") + "/33j4ks.$$$";

getdir

The getdir() returns the working value in use by the application for any one of the following constants (string literal/manifest):
	"Fonts"/FONTSDIR              Modeler
	"Macros"/MACROSDIR            Modeler
	"Install"/INSTALLDIR          Layout/Modeler   (LightWave Installation Directory)
	"Objects"/OBJECTSDIR          Layout/Modeler
	"Images"/IMAGESDIR            Layout/Modeler
	"Motions"/MOTIONSDIR          Layout/Modeler
	"Temp"/TEMPDIR                Layout/Modeler
	"Plugins"/PLUGINSDIR          Layout/Modeler
	"Settings"/SETTINSDIR         Layout/Modeler   (Location of alternate configurations)
	"Content"/CONTENTDIR          Layout
	"Scenes"/SCENESDIR            Layout
	"Hierarchies"/HIERARCHIESDIR  Layout
	"Surfaces"/SURFACESDIR        Layout
	"Output"/OUTPUTDIR            Layout
	"Animations"/ANIMATIONSDIR    Layout
	"Envelopes"/ENVELOPESDIR      Layout
	"Previews"/PREVIEWSDIR        Layout
	"Command"/COMMANDDIR          Layout
You might retrieve one of these directory values in the following fashion:

         ...
         install = getdir("Install");
         ...
         plugins = getdir(PLUGINSDIR);
         ...

sleep

The sleep() command allows a script to pause for a specified number of milliseconds, releasing the script's (and Modeler's) Windows time slice until the sleep time has expired.

For the purposes of conversion, 1000 milliseconds is equal to 1 second.

     sleep(1000);   // sleep for 1 second

dump

dump() is a debug function. It allows the script developer to dump all known internal script variables and their values to a specified text file. The text file specified, if it already exists, will be appended to each time this function is called.

     dump("/myscript.var");
The dump() command is not supported in the run-time environment. Scripts containing this command will not compile successfully with the BMC Script Compiler.

store, recall

This pair of commands offer a script the ability to retain variable values across invocations.

The store() command takes two parameters. The first parameter is a string literal (or variable with a character string) that uniquely identifies the value to be stored. The second parameter is the actual value itself.

recall() retrieves values that have been previously store()'d. As with store(), it too takes two parameters. The first, like store(), is the value identifier that was originally used to retain the value. Unlike store(), however, the second parameter is a default value to return if a store() has never been issued for that identifier.

The following LScript illustrates the uses of these two commands. When executed more than once, the values stored will change.

     main
     {
          heading = recall("heading",15);
          testing = recall("testing",95.34);
          myName = recall("myName","Bob Hood");
          newName = recall("newName",
                              string(myName," has no life!"));

          info("got heading == ",heading,
                    ", testing == ",testing);
          info("got myName == ",myName,
                    ", newName == ",newName);

          store("heading",++heading);
          store("testing",testing + .5);
          store("myName",myName);
          store("newName",newName);
     }

strleft, strright, strsub, strupper, strlower

This suite of string-handling functions allows a script programmer to manipulate LScript character strings with a fine granularity.

strleft() and strright() return a portion of a character string beginning from the indicated direction. They both accept two parameters, where the first is the character string to be processed, and the second is a numeric count of the number of characters to extract.

     // the following prints 'My first name is "Ted"'

     info("My first name is \"",
          strleft("Ted Philmore",3"),"\");
strsub() is another extraction function. However, this function allows you to extract an arbitrary number of characters from within the string starting from an arbitrary location, instead of starting from one of its ends.

     t = strsub("Ted Philmore",3,3);    // returns "d P"
As their names imply, strupper() and strlower() return a copy of the provided string as either all upper- or lower-case characters, respectively.

In all cases, the original string provided is not modified.


Next Section Previous Section Table of Contents Index Errata
© 1996 Virtual Visions, Inc.
© 1997 NewTek, Inc.